<?php

namespace app\common\model;

use basic\ModelBasic;

class Service extends ModelBasic
{
	use \traits\ModelTrait;

	 /**
     * 列表
     * @Author   FW
     * @DateTime 2020-09-24
     * @Email    123763712@qq.com
     * @param    [type]
     * @return   [type]
     */
    public static function getList($where){
        $count = self::setWhere($where)->count();
        $data  = [];
        if ( $count == 0 ) {
            return compact('data','count');
        }

        $data=self::setWhere($where,'m')
        ->field("m.*,org.organ_name,sch.school_name,ifnull(cat.cate_name,'默认') as cate_name,ifnull(sp.is_open,0) as sp_is_open,sp.share_poster")
        ->join('__ORGAN__ org','m.org_id=org.id' , 'left')
        ->join('__SCHOOL__ sch','m.school_id=sch.id' , 'left')
        ->join('__CATEGORY__ cat','m.cate_id=cat.id' , 'left')
        ->join('__DISTRIBUTION_SEPARATE__ sp',sprintf('m.id=sp.relation_id AND sp.relation_type=%d',DistributionSeparate::REL_TYPE_SERVICE) , 'left')
        ->page($where['page'] ?? 1,$where['limit'] ?? 10)
        ->select();

        if ( !empty($data) ) {
            $data = $data->toArray();
            $data = static::process_list($data);
        }

        return compact('data','count');
    }

    /**
     * [getOne description]
     * @Author   FW
     * @DateTime 2021-01-12
     * @Email    123763712@qq.com
     * @param    [type]           $id [description]
     * @return   [type]               [description]
     */
    public static function getOne ($id)
    {
        $item = self::alias('m')->where('m.id',$id)
            ->field("m.*,org.organ_name,sch.school_name,ifnull(cat.cate_name,'默认') as cate_name,ifnull(sp.is_open,0) as sp_is_open,sp.share_poster,ifnull(pink.status,0) as pink_is_open,ifnull(pink.pink_price,0) as pink_price,ifnull(pink.pink_nums,0) as pink_nums,ifnull(pink.start_time,'') as pink_start_time,ifnull(pink.end_time,'') as pink_end_time")
            ->join('__ORGAN__ org','m.org_id=org.id' , 'left')
            ->join('__SCHOOL__ sch','m.school_id=sch.id' , 'left')
            ->join('__CATEGORY__ cat','m.cate_id=cat.id' , 'left')
            ->join('__DISTRIBUTION_SEPARATE__ sp',sprintf('m.id=sp.relation_id AND sp.relation_type=%d',DistributionSeparate::REL_TYPE_SERVICE) , 'left')
            ->join('__PINK_CONFIG__ pink',"m.id=pink.rel_id AND pink.rel_type='service' AND pink.status=1" , 'left')
            ->find();

        if ( empty($item) ) {
            return [];
        }

        $item = $item->toArray();

        $item['detail'] = htmlspecialchars_decode(CommonDetail::where(['rel_type'=>'service','rel_id'=>$item['id']])->value('detail'));

        return static::process_list([$item])[0];
    }

     /**
     * 处理列表数据
     * @Author   FW
     * @DateTime 2021-01-12
     * @Email    123763712@qq.com
     * @param    array            $list [description]
     * @return   [type]                 [description]
     */
    public static function process_list (array $list)
    {
        foreach ($list as $key => &$value) {
            $value['price'] *= 1;
            $value['original_price'] *= 1;

            $value['status_text']      = static::$common_status[$value['status']] ?? '-';

            $value['cover'] = json_decode($value['cover']);
            $value['label'] = json_decode($value['label']);
        }
        return $list;
    }

	/**
	 * 设置where条件
	 * @Author   FW
	 * @DateTime 2021-01-12
	 * @Email    123763712@qq.com
	 * @param    [type]           $where [description]
	 * @param    string           $alias [description]
	 * @param    [type]           $model [description]
	 */
	public static function setWhere($where,$alias='m',$model=null){
        $model = $model===null ? new self() : $model;

        $model->alias($alias);

        if ( isset($where['org_id']) && $where['org_id'] > 0 ) {
            $org_id = $where['org_id'] + 0;
        } else {
            $org_id = static::getBelongOrganId();
        }
        if ( $org_id > 0 ) {
            $model->where(sprintf('%s.org_id=%d' , $alias , $org_id));
        }

        if ( isset($where['school_id']) && $where['school_id'] > 0 ) {
            $school_id = $where['school_id'] + 0;
        } else {
            $school_id = static::getBelongSchoolId();
        }

        if ( $school_id > 0 ) {
            $model->where($alias.'.school_id',$school_id);
        }

        if ( static::$softDelete ) {
        	$model->where($alias.'.is_del',0);
        }

        if ( isset($where['name']) && $where['name'] != '' ) {
            $model->where( sprintf('%s.name' , $alias) . ' LIKE ' . "'%" . $where['name'] ."%'");
        }

        if ( isset($where['cate_id']) && $where['cate_id'] > 0 ) {
            $model->where(sprintf('%s.cate_id = %d' , $alias, $where['cate_id']));
        }

        if ( isset($where['is_rmt']) && $where['is_rmt'] > 0 ) {
            $model->where(sprintf('%s.is_rmt = 1' , $alias));
        }

        /** 选择用户已购 */
        if ( isset($where['uid']) && $where['uid'] > 0 ) {
            //$model->where(sprintf("%s.id IN (SELECT rel_id FROM eb_bought_service WHERE uid = %d AND status = 1 AND rel_type='service')" , $alias, $where['uid']));
        }

        if ( isset($where['order']) && $where['order'] != '' ) {
            $model->order(sprintf('%s.%s' , $alias, $where['order']));
        } else {
            $model->order(sprintf('%s.id ASC' , $alias));
        }

        return $model;
    }

    /**
     * 主数据保存后回调
     * @Author   FW
     * @DateTime 2021-08-10
     * @Email    123763712@qq.com
     * @param    [type]           $prk_id [description]
     * @param    array            $data   [description]
     * @return   [type]                   [description]
     */
    public static function afterSave ( $prk_id , array $data )
    {
        if ( !isset($data['detail']) ) return true;

        return CommonDetail::saveOne([
            'rel_type'    =>    'service',
            'rel_id'      =>    $prk_id,
            'detail'      =>    htmlentities($data['detail'])
        ]);
    }

     /**
     * 选择已购套餐预检查以及返回正确数据格式
     * @Author   FW
     * @DateTime 2021-08-11
     * @Email    123763712@qq.com
     * @param    [type]           $id [description]
     */
    public static function ConsumePrecheck ( $svc_id , $bought_id = 0 )
    {
        if ( $bought_id > 0 ) {
            $service = BoughtService::alias('b')
            ->field('0 as price,svc.name as rel_name,b.rel_type,b.rel_id,b.bought_qty')
            ->join('__SERVICE__ svc' , 'svc.id = b.rel_id' , 'left')
            ->where(['b.id' => $bought_id, 'b.status' => 1])
            ->find();
        } else {
            $service = Service::alias('svc')
            ->field("svc.price, svc.name as rel_name,'service' as rel_type, id as rel_id,999 as bought_qty")
            ->where('id' , $svc_id)
            ->find();
        }

        if ( empty($service) ) throw new \think\exception\ValidateException('校验失败【0901】');

        $valid['item_ukey'] = md5($service->rel_type . '_' . $service->rel_id . '_' . $bought_id);
        $valid['pck_id']    = 0;
        $valid['rel_type']  = $service->rel_type;
        $valid['rel_id']    = $service->rel_id;
        $valid['rel_name']  = $service->rel_name;
        $valid['bought_id'] = $bought_id;
        $valid['price']     = $service->price;
        $valid['qty']       = 1;
        $valid['disc_amt']  = 0;
        $valid['max_nums']  = $service->bought_qty;
        return $valid;
    }
}//Class End
